<template>
  <el-upload
    id="audioUpload"
    ref="uploadRef"
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :multiple="false"
    :file-list="fileList"
    :limit="props.numLimit"
    :http-request="uploadSectionFile"
    :before-upload="beforeAvatarUpload"
    :on-preview="handleChangeAudio"
    :on-success="handleAvatarSuccess">
    <el-button slot="trigger" plain icon="Download" type="primary" style="margin: 0 10px;" :loading-icon="Eleme" :loading="loading">{{ props.btntext }}</el-button>
</el-upload>
</template>

<script setup lang='ts'>
import { ref, reactive } from 'vue';
import OSS from 'ali-oss';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { Eleme } from '@element-plus/icons-vue'

const { proxy } = useCurrentInstance()
let emit = defineEmits(['upload-success'])
let fileList = ref([])
let audioSrc = ref('')
let uploadRef = ref()
let loading = ref(false)
const props = defineProps({
  numLimit: {
    // 最大允许上传个数
    type: Number,
    default: 1
  },
  btntext: {
    // 已上传图片服务器路径
    type: String,
    default:'选取文件'
  }
})
let config = reactive({
  aliyunServerURL:'',
  accessid:'',
  AccessKeySecret:'',
  expiration:'',
  SecurityToken:'',
  policyBase64:'',
  signature:''
})
const handleChangeAudio = (data) => {
  if(data.raw){
    audioSrc.value = URL.createObjectURL(data.raw)
  }else{
    audioSrc.value = data.url
  }
}
const handleAvatarSuccess = (response,file, uploadFiles) => {
  // proxy.$message({
  //   type:'success',
  //   message:'上传成功'
  // })
  // emit('upload-success',response)
  console.log(response,'上传成功')
}
var testmsg = ref()
const beforeAvatarUpload = (file) => {
  // 文件类型进行判断
  testmsg.value=file.name.substring(file.name.lastIndexOf('.')+1)
  const isAudio = testmsg.value === 'xls' || testmsg.value === 'xlsx'
  if (!isAudio) {
    proxy.$message.error("上传文件只能是xls或xlsx格式!");
      fileList.value = [];
  }
  return isAudio
}

//上传进度条
const progress = (p, checkpoint) => {
  if(Math.floor(p* 100) == 100){
    loading.value = false
  }
}
const uploadSectionFile = (option) => {
  let file = option.file
  loading.value = true
  proxy.$api.uploadFile({file_type:'file'}).then(res => {
    // 定义上传文件的名字+后缀
    const aliyunilFeKey = res.result.token.Path + new Date().getTime() + Math.floor(Math.random() * 150) + `.${testmsg.value}`
    config.aliyunServerURL=`https://${res.result.token.Bucket}.${res.result.token.Region}.aliyuncs.com/`
    let client = new OSS({
        accessKeyId: res.result.token.AccessKeyId,
        accessKeySecret: res.result.token.AccessKeySecret,
        stsToken: res.result.token.SecurityToken,
        region: res.result.token.Region,
        bucket: res.result.token.Bucket,
        secure:true
    })

    // 调用oss上传接口
    client.multipartUpload(aliyunilFeKey, file, {progress}).then(response=>{
      if (response.res.status === 200) {
        emit('upload-success',config.aliyunServerURL+aliyunilFeKey)
      }else{
        loading.value = false
      }
    }).catch(function (err) { console.error('error: ', err) })
  }).catch(err => loading.value = false)
}
// 清空上传列表
const clearFiles = () => {
  uploadRef.value.clearFiles()
}
defineExpose({clearFiles})
</script>

<style lang='scss' scoped>
audio {
  width: 100%;
  height: 10.666667rem;
  outline: none;
}
</style>
